from django import forms
from django.conf import settings
import dmarkups.models


class MarkupChoose(forms.Select):
    def __init__(self, attrs=None, markup_choices=None):
        super(MarkupChoose, self).__init__(attrs=attrs, choices=[(mkey, mname) for (mkey, (mname, mfunc)) in markup_choices.iteritems()])

class MarkupContent(forms.Textarea):
    pass
    # TODO: implement JS thingie ma dong...
    
class MarkupWriter(forms.MultiWidget):
    choices = [] # TODO: Check this out; This has something to do with ForeignKey (I suspect :-D) But in short, this doesn't run without it.
    markup_model = dmarkups.models.Markup
    
    def __init__(self, widgets=None, attrs=None, markup_model=None, markup_choices=None):
        self.markup_model = markup_model or self.markup_model
        
        if widgets is None:
            # TODO: limit_markups is not passed on
            widgets = (MarkupChoose(attrs={'class':'MarkupChoose'}, markup_choices=markup_choices), 
                       MarkupContent(attrs={'class':'MarkupContent'}), 
                       forms.HiddenInput())
        
        super(MarkupWriter, self).__init__(widgets, attrs)
        
    def decompress(self, value):
        try:
            markup = self.markup_model.objects.get(pk=value)
        except self.markup_model.DoesNotExist, mr:
            return [None,None,None] # TODO: Maybe the default values oughta be here
        return [markup.markup, markup.content, value] # TODO: Here are the hardcoded requirements for `markup_model`
    
    def render(self, name, value, attrs=None):
        # TODO: Is this too much hardcoded? Do we need some attrs magic to make unique attrs to *just* this?
        return "<span class=\"MarkupWriter\">%s</span>" % super(MarkupWriter, self).render(name, value, attrs)
    
    class Media:
        css = {
               'all': ('%sdmarkups/markupwriter.css' % settings.MEDIA_URL,)
        }
        js = ('%sdmarkups/markupwriter.js' % settings.MEDIA_URL,)
        
#def markupchoose_factory(include_markups, exclude_markups):
    #LimitedMarkupChoose = type('LimitedMarkupChoose', (dmarkups.widgets.MarkupChoose, ), {})
    #LimitedMarkupChoose.limit_markups = limit_markups
    #return LimitedMarkupChoose
    
def markupwriter_factory(markup_model):
    """Customized markup model MarkupWriter
    
    `markup_model` - Model for saving the markups, should have fields:
        `markup`, `content`, `rendered_content`    
    """
    dynamicMarkupWriter = type('MarkupWriter_%s' % markup_model.__name__, (MarkupWriter, ), {})
    dynamicMarkupWriter.markup_model = markup_model
    return dynamicMarkupWriter
